// pages/mine/mine-carinfo/mine-carinfo.js
import { toast } from '../../../../utils/Tools'
const app = getApp()
Page({
  data: {
    id:null,
    getCarImg:[]
  },
  onLoad: function (options) {
    const {images,id} = wx.getStorageSync('driver_user');
    const uploadImg = wx.getStorageSync('uploadImg') || [];
    if(images && uploadImg.length<1){
      this.setData({
        getCarImg: images,
        id
      })
    }else{
      this.setData({
        getCarImg: uploadImg
      })
    }
  },
  handleChooseImg(e){ //   选择图片事件
    wx.chooseImage({   //   选择图片
      count: 1,
      success: res=>{
        console.log(res)
        const oImage = {name:e.currentTarget.dataset.name,urls:res.tempFilePaths[0]}  //    上传选择后的图片集
        //  首次上传  替换图片
        const value = `getCarImg[${e.currentTarget.dataset.index}]`
        this.setData({
          [value]: oImage
        })
      }
    });
  },
  handleUpload(){ //  点击上传
    wx.showModal({
      title: '操作提醒',
      content: '是否提交上传图片',
      showCancel: true,
      success: (result) => {
        if(result.confirm){
          if(this.data.getCarImg.length<3){
            toast('请上传3张图片',null,1000)
            return
          }
          for(let i=0;i<this.data.getCarImg.length;i++){
            wx.uploadFile({
              url: app.globalData.BASE_URL+'api/driver/car_info',
              filePath: this.data.getCarImg[i].urls,
              name: this.data.getCarImg[i].name,
              formData: {
                id: this.data.id,
                name: this.data.getCarImg[i].name,
                token: wx.getStorageSync('token')
              }, 
              header: {
                "Content-Type": "multipart/form-data"
              },
              success: res => {
                console.log(res)
                const result = JSON.parse(res.data)
                wx.setStorageSync('uploadImg', result.data.images);
                toast('上传成功','success',2000)
                setTimeout(()=>{
                  wx.reLaunch({
                    url: '/driver_side/pages/mine/index/index',
                  })
                },2000)
              },
              fail: err =>{
                
              }
            })
          }          
        }else{
          toast('点击了取消')
        }
      }
    });
  }
})